package com.damuzee.system.admin.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.damuzee.core.web.WebErrors;
import com.damuzee.core.web.session.SessionProvider;
import com.damuzee.system.admin.Constaints;
import com.damuzee.system.admin.domain.EmpUser;
import com.damuzee.system.admin.service.EmpUserService;
import com.google.code.kaptcha.Constants;

@Controller
public class AdminLoginAct {
	private static final Logger log = LoggerFactory.getLogger(AdminLoginAct.class);


	@RequestMapping(value = "/login.do", method = RequestMethod.GET)
	public String input(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
	 
		return "/login";
	}
	
	@RequestMapping(value = "/register.do", method = RequestMethod.GET)
	public String register(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
	 
		return "/register";
	}
	
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public String submit(String username, String password, String captcha,
			String processUrl, String returnUrl, String message,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		
		WebErrors errors = validateSubmit(username, password, captcha, request, response);
		if (!errors.hasErrors()) {
			EmpUser user = userSerivce.adminLogin(username,password);
			session.setAttribute(request, response, Constaints.AUTH_KEY, username);
			if(user != null){
				return "redirect:index.do" ;
 			}
			errors.addErrorCode("errors.usernotexis");
		}
		// 登录失败
		errors.toModel(model);
		
		return "/login";
	}
	
	
	private WebErrors validateSubmit(String username, String password,
			String captcha, HttpServletRequest request,
			HttpServletResponse response) {
		WebErrors errors = WebErrors.create(request);
		if (errors.isOutOfLength(username, "username", 1, 100)) {
			return errors;
		}
		if (errors.isOutOfLength(password, "password", 1, 32)) {
			return errors;
		}
		// 如果输入了验证码，那么必须验证；如果没有输入验证码，则根据当前用户判断是否需要验证码。
		if (!StringUtils.isBlank(captcha)) {
			if (errors.isBlank(captcha, "captcha", 100)) {
				return errors;
			}
		 
			String codeString = (String)session.getAttribute(request,Constants.KAPTCHA_SESSION_KEY); 
			if (!captcha.equals(codeString)) {
		 
				errors.addErrorCode("error.invalidCaptcha");
				return errors;
			}
		}
		return errors ;
	}
	
 
	 

	@Resource
	private SessionProvider session;
	@Resource
	private EmpUserService userSerivce ;

}
